package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.StoreRepository;
import cn.hd01.repository.entity.Store;
import cn.hd01.service.StoreService;

@Service
public class StoreServiceImpl extends BaseServiceImpl<Store, Integer> implements StoreService {

	private StoreRepository repository;

	@Autowired
	public StoreServiceImpl(StoreRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public Page<Store> find(final Store query, Pageable pageable) {
		if (query == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<Store>() {
			@Override
			public Predicate toPredicate(Root<Store> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();

				if (StringUtils.hasText(query.getName())) {
					predicates.add(cb.like(r.get("name").as(String.class), "%" + query.getName() + "%"));
				}

				if (StringUtils.hasText(query.getAddress())) {
					predicates.add(cb.like(r.get("address").as(String.class), "%" + query.getAddress() + "%"));
				}

				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}

	@Override
	public boolean exists(String name) {
		return repository.countByName(name) != 0;
	}
}
